#!/usr/bin/env python3
# -*- coding: utf-8 -*-
from playhouse.pool import PooledMySQLDatabase
from playhouse.reflection import generate_models
import peewee

from lj_tool import tool_cache, tool_log, tool_url
from lj_tool.tool_opt import v


def is_auto_pri(db, tname):
    sql = "SELECT COLUMN_NAME, EXTRA FROM information_schema.COLUMNS WHERE TABLE_SCHEMA = %s AND TABLE_NAME = %s AND COLUMN_KEY = 'PRI'"

    database = db.database

    with db.connection_context() as conn:
        cursor = conn.cursor()
        cursor.execute(sql, (database, tname))
        res = cursor.fetchall()
        cursor.close()
        return res[0][1] == "auto_increment"


@tool_cache.lj_wrapper_cache("lj_orm_models", 60 * 60 * 24 * 30)
def models(ds_id):
    db = init_db(ds_id)
    return generate_models(db)


@tool_cache.lj_wrapper_cache("lj_orm_init_db", 60 * 60 * 24 * 30)
def init_db(ds_id=None):
    if not ds_id:
        tool_log.log.info(
            f"LJ - 数据库链接[默认]建立...")
        return PooledMySQLDatabase(
            'ntd_server',
            host='com-server.rwlb.rds.aliyuncs.com',
            port=3306,
            user='opendb',
            password='Fmhb2022!@#',
            max_connections=20,
        )

    data_source_model = gen_model("data_source")
    ds = data_source_model.get_by_id(ds_id)

    url_obj = tool_url.parse_url(ds.link_address)

    tool_log.log.info(
        f"LJ - 数据库链接[{ds.link_address}][{url_obj.get('host')}:{url_obj.get('port')}[{url_obj.get('path')}]]建立...")

    port = None
    if url_obj.get('port'):
        port = int(url_obj.get('port'))

    return PooledMySQLDatabase(
        url_obj.get('path'),
        host=url_obj.get('host'),
        port=port,
        user=ds.account,
        password=ds.password,
        max_connections=20,
    )

# 动态创建模型类


@tool_cache.lj_wrapper_cache("lj_orm_gen_model")
def gen_model(tname, ds_id=None):
    # print(f"LJ - 获取模型 - {tname}[{ds_id}]")
    if ds_id == "default":
        ds_id = None

    return models(ds_id).get(tname)
